package user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import db.BeanUtilities;
import db.HibernateUtil;
import db.Users;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public Register() {
        super();
    }

	/**
	 * Rejestracja uzytkownika
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		session.setAttribute("error", "Dostep zabrioniony");
		response.sendRedirect("/runWithJava/");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Users user = new Users();
		BeanUtilities.populateBean(user, request.getParameterMap());
	    HibernateUtil<Users> hu = new HibernateUtil<Users>();
	    try{
	    	hu.create(user);
	    	HttpSession session = request.getSession(true);
	    	session.setAttribute("user", user);	
	    	response.sendRedirect("/runWithJava/");
	    } catch(Exception e) {
		      HttpSession session = request.getSession(true);
		      session.setAttribute("error", e.getMessage());
		      session.setAttribute("errorObject", user);
		      response.sendRedirect("/runWithJava/rejestracja.html");
	    }
	}

}
